import 'package:flutter/material.dart';

class LocalKeyPage extends StatefulWidget {
  const LocalKeyPage({super.key});

  @override
  State<LocalKeyPage> createState() => _LocalKeyPageState();
}

class _LocalKeyPageState extends State<LocalKeyPage> {
  final List<Widget> _list = [
    //注意常量没法改变

    //1.可以保存状态   2.排序
    _BoxState(color: Colors.red, key: ValueKey(1)),
    _BoxState(
      color: Colors.yellow,
      key: UniqueKey(), //唯一值  每次执行随机生成
    ),
    _BoxState(
      color: Colors.blue,
      key: ObjectKey(new _BoxState(color: Colors.blue)),//传入一个对象
    ),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _list.shuffle(); //打乱list顺序
          });
        },
        child: Icon(Icons.refresh),
      ),
      appBar: AppBar(title: Text('LocalKey局部key')),
      body: Center(
        child: Column(
          spacing: 20,
          mainAxisAlignment: MainAxisAlignment.center,
          children: _list,
        ),
      ),
    );
  }
}

class _BoxState extends StatefulWidget {
  final double width;
  final double height;
  final Color color;
  // final Key key;
  _BoxState({
    super.key,
    this.width = 100,
    this.height = 100,
    this.color = Colors.red,
  });

  @override
  State<_BoxState> createState() => __BoxStateState();
}

class __BoxStateState extends State<_BoxState> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      // color: widget.color,
      child: ElevatedButton(
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: widget.color,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        child: Text(
          '$_count',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
      ),
    );
  }
}
